<template>
	<view v-if="state===1" class="inline-flex center px-8 py-4 radius-16 color-primary fs-12 font-normal" style="background:#FFF0EA;" @click.stop="toSubscribe">
		<image class="size-20 mr-2" src="@/static/svg/icon-plus-red.svg"></image>
		<text>订阅</text>
	</view>
	<view v-else class="inline-flex center px-8 py-4 radius-16 color-primary fs-12 font-normal" style="background:#FFF0EA;" @click.stop="toCancelSubscribe">
		<text>取消订阅</text>
	</view>
</template>

<script setup>
	import { businessSubscribeUpdateStateApi } from '@/api/business.js'
	
	const props = defineProps({
		state: {
			type: Number,
			default: 1 // 订阅状态：1-未订阅，2-已订阅
		},
		businessId: {
			type: Number
		},
		userId: {
			type: [Number, String]
		},
	})
	
	const emits = defineEmits(['onStateChange'])

	const toSubscribe = () => {
		if (props.userId) {
			businessSubscribeUpdateStateApi({
				businessId: props.businessId,
				userId: props.userId,
				subscribeState: 1, // 订阅状态：1-订阅，2-取消订阅
			}).then(res => {
				if (res) {
					uni.showToast({
						icon: 'none',
						title: '订阅成功'
					})
				}
				emits('onStateChange', res)
			}).catch(console.error)
		} else {
			uni.navigateTo({
				url: '/pagesA/login/login'
			})
		}
	}
	
	const toCancelSubscribe = () => {
		businessSubscribeUpdateStateApi({
			businessId: props.businessId,
			userId: props.userId,
			subscribeState: 2, // 订阅状态：1-订阅，2-取消订阅
		}).then(res => {
			if (res) {
				uni.showToast({
					icon: 'none',
					title: '取消订阅成功'
				})
			}
			emits('onStateChange', res)
		}).catch(console.error)
	}
</script>
